使用Java中的两个线程打印1-20号 [英] Print numbers 1-20 with two threads in Java
本文介绍了使用Java中的两个线程打印1-20号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用两个线程打印数字1-20:
I'm trying to print numbers 1-20 with two threads:
- 连线程 - 只打印偶数。
- 奇数线程 - 仅打印奇数。
我还有一个用于同步的锁定对象。
I also have a lock object for synchronization.
我的申请被卡住了。你能告诉我这是什么问题吗?
My application is stuck. Can you tell me what is the problem?
我的代码:
public class runIt
{
public static void main(String[] args)
{
Odd odd = new Odd("odd thread");
Even even = new Even("even thread");
odd._t.start();
even._t.start();
try{
odd._t.join();
even._t.join();
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
public class Constants{
static Object lock = new Object();
}
public class Even implements Runnable{
Thread _t;
String _threadName;
public Even(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 0){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
public class Odd implements Runnable{
Thread _t;
String _threadName;
public Odd(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 1){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e1){
e1.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
我的输出应为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
感谢您的帮助,
Tam。
Thank you for the assistance, Tam.
推荐答案
以下代码对某人有帮助,
Below code will help to someone,
public class MyClass {
private static Object lock = new Object();
public static void main(String args[]){
Runnable runnable1 = new Runnable() {
@Override
public void run() {
for(int i=1; i<20; i=i+2){
synchronized (lock) {
System.out.println("Thread 1: "+i);
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
System.out.println("Error in Thread 1: "+e.getMessage());
}
}
}
}
};
Runnable runnable2 = new Runnable() {
@Override
public void run() {
for(int i=2; i<=20; i=i+2){
synchronized (lock) {
System.out.println("Thread 2: "+i);
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
System.out.println("Error in Thread 2: "+e.getMessage());
}
}
}
}
};
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
System.out.println("Thread Start: ");
thread1.start();
thread2.start();
}
}
这篇关于使用Java中的两个线程打印1-20号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文