线程的生命周期
线程同步的两种方法实现
方式一: 同步代码块
方式一
: 同步代码块 使用实现Runnable接口的方式
class WThread implements Runnable {
private int ticket
= 100;
Object obj
= new Object();
@Override
public void run() {
while (true) {
synchronized (this) {
if (ticket
> 0) {
try {
Thread
.sleep(100);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
System
.out
.println(Thread
.currentThread().getName() + " 卖票,票号为: " + ticket
);
ticket
--;
} else {
break;
}
}
}
}
public static class WindowTest1 {
public static void main(String
[] args
) {
WThread wThread
= new WThread();
Thread t1
= new Thread(wThread
);
Thread t2
= new Thread(wThread
);
Thread t3
= new Thread(wThread
);
t1
.setName("窗口1");
t2
.setName("窗口2");
t3
.setName("窗口3");
t1
.start();
t2
.start();
t3
.start();
}
}
}
方式一
: 同步代码块 使用继承Thread类的方式实现
class Window extends Thread{
private static int ticket
= 100;
static Object obj
=new Object();
@Override
public void run() {
while (true){
synchronized(Window
.class){
if (ticket
> 0){
try {
Thread
.sleep(100);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
System
.out
.println(getName() + ": 买票,票号为: "+ ticket
);
ticket
--;
}else{
System
.out
.println(getName() + "票已售空");
break;
}
}
}
}
}
public class WindowTest {
public static void main(String
[] args
) {
Window w1
= new Window();
Window w2
= new Window();
Window w3
= new Window();
w1
.setName("窗口1");
w2
.setName("窗口2");
w3
.setName("窗口3");
w1
.start();
w2
.start();
w3
.start();
}
}
方式二: 同步方法
方式二
: 同步方法 实现Runnable接口
class WThread2 implements Runnable {
private int ticket
= 100;
@Override
public void run() {
while (ticket
> 0) {
show();
}
}
private synchronized void show(){
if (ticket
> 0) {
try {
Thread
.sleep(100);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
System
.out
.println(Thread
.currentThread().getName() + " 卖票,票号为: " + ticket
);
ticket
--;
}
}
}
public class WindowTest2 {
public static void main(String
[] args
) {
WThread2 wThread2
= new WThread2();
Thread t1
= new Thread(wThread2
);
Thread t2
= new Thread(wThread2
);
Thread t3
= new Thread(wThread2
);
t1
.setName("窗口1");
t2
.setName("窗口2");
t3
.setName("窗口3");
t1
.start();
t2
.start();
t3
.start();
}
}
方式二
: 同步方法 继承Thread类
class Window3 extends Thread{
private static int ticket
= 100;
@Override
public void run() {
while (true){
show();
}
}
private static synchronized void show(){
if (ticket
> 0){
try {
Thread
.sleep(100);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
System
.out
.println(Thread
.currentThread().getName() + ": 买票,票号为: "+ ticket
);
ticket
--;
}
}
}
public class WindowTest3 {
public static void main(String
[] args
) {
Window3 w1
= new Window3();
Window3 w2
= new Window3();
Window3 w3
= new Window3();
w1
.setName("窗口1");
w2
.setName("窗口2");
w3
.setName("窗口3");
w1
.start();
w2
.start();
w3
.start();
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-35311.html