分别写一个JAVA多线程创建、同步、互斥、等待、唤醒程序
时间: 2023-06-04 18:07:52 浏览: 64
JAVA多线程创建程序:
```
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running.");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
```
JAVA多线程同步程序:
```
class Counter {
int count;
synchronized void increment() {
count++;
}
}
public class MyThread implements Runnable {
Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
// do something
counter.increment();
// do something else
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new MyThread(counter));
Thread t2 = new Thread(new MyThread(counter));
t1.start();
t2.start();
// wait for threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// handle exception
}
System.out.println(counter.count); // should be 2
}
}
```
JAVA多线程互斥程序:
```
class Counter {
int count;
synchronized void increment() {
count++;
}
}
public class MyThread implements Runnable {
Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
// do something
synchronized (counter) {
counter.increment();
}
// do something else
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new MyThread(counter));
Thread t2 = new Thread(new MyThread(counter));
t1.start();
t2.start();
// wait for threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// handle exception
}
System.out.println(counter.count); // should be 2
}
}
```
JAVA多线程等待程序:
```
class MyThread implements Runnable {
public void run() {
try {
System.out.println("Thread started.");
Thread.sleep(5000);
System.out.println("Thread ended.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
// wait for thread to finish
try {
t.join();
} catch (InterruptedException e) {
// handle exception
}
System.out.println("Main program ended.");
}
}
```
JAVA多线程唤醒程序:
```
class MyThread implements Runnable {
volatile boolean running = true;
public void run() {
while (running) {
System.out.println("Thread running.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
System.out.println("Thread stopped.");
}
public void stop() {
running = false;
}
public static void main(String[] args) {
MyThread t = new MyThread();
Thread thread = new Thread(t);
thread.start();
// wait for thread to run for 5 seconds
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// handle exception
}
// wake up thread
t.stop();
}
}
```