两个线程同步输出0-100Java代码
时间: 2023-03-10 09:52:40 浏览: 75
应该这样:public class TwoThreads {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread());
Thread t2 = new Thread(new MyThread());
t1.start();
t2.start();
}
}class MyThread implements Runnable {
public void run() {
for(int i=0; i<=100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
相关问题
java 创建两个线程 一个输出1-100的奇数,一个输出1-100的偶数 交替输出
在Java中,我们可以使用 `synchronized` 关键字和 `wait()`、`notify()` 方法来实现线程的交替输出。下面是一个示例代码:
```java
class OddEvenPrinter {
private int count;
private int maxCount;
public OddEvenPrinter(int maxCount) {
this.maxCount = maxCount;
this.count = 1;
}
public synchronized void printOdd() throws InterruptedException {
while (count <= maxCount) {
if (count % 2 != 0) {
System.out.println(count);
count++;
notify();
} else {
wait();
}
}
}
public synchronized void printEven() throws InterruptedException {
while (count <= maxCount) {
if (count % 2 == 0) {
System.out.println(count);
count++;
notify();
} else {
wait();
}
}
}
}
public class Main {
public static void main(String[] args) {
OddEvenPrinter printer = new OddEvenPrinter(100);
Thread oddThread = new Thread(() -> {
try {
printer.printOdd();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread evenThread = new Thread(() -> {
try {
printer.printEven();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
oddThread.start();
evenThread.start();
}
}
```
在这个代码中,我们创建了一个名为 `OddEvenPrinter` 的类,它有一个 `count` 变量来表示当前要输出的数字,和一个 `maxCount` 变量来表示最大的数字。`printOdd()` 方法用于输出奇数,`printEven()` 方法用于输出偶数。
在每个方法中,我们使用 `synchronized` 关键字来确保线程的同步。在 `printOdd()` 方法中,当 `count` 为奇数时输出数字并递增,然后调用 `notify()` 方法唤醒等待的线程;如果 `count` 为偶数,则调用 `wait()` 方法使线程等待。在 `printEven()` 方法中同理。
在 `main()` 方法中,我们创建了两个线程 `oddThread` 和 `evenThread`,分别执行 `printOdd()` 和 `printEven()` 方法。然后启动这两个线程,它们将交替输出奇偶数。
线程同步与互斥Java代码
线程同步和互斥是确保多个线程正确协同工作的关键。在Java中,可以通过使用`synchronized`关键字来实现线程同步和互斥。下面是一个简单的示例代码:
```java
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
MyThread thread1 = new MyThread(counter);
MyThread thread2 = new MyThread(counter);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount());
}
}
```
在这个示例代码中,`Counter`类是一个计数器,包含两个同步方法:`increment()`和`getCount()`。`increment()`方法递增计数器的值,`getCount()`方法返回计数器的当前值。`MyThread`类是一个线程,它接收一个`Counter`对象并在其`run()`方法中重复调用`increment()`方法。在`main()`方法中,创建两个`MyThread`对象并启动它们。使用`join()`方法等待这两个线程完成,然后输出计数器的值。
使用`synchronized`关键字确保`increment()`和`getCount()`方法在同一时刻只能被一个线程访问。这样可以确保计数器的值在多个线程之间同步,并避免竞态条件的问题。