Ber*_*ard 21 java multithreading
我正在尝试创建两个线程,一个线程显示从0到10的整数,一个线程显示从1到11的奇数.以下代码是否适合设计此程序?
public class Mythread {
public static void main(String[] args) {
Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}
class Runnable2 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 0)
System.out.println(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 42
@aymeric的答案不会按自然顺序打印数字,但这段代码会.最后解释.
public class Driver {
static Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int itr = 1; itr < 51; itr = itr + 2) {
synchronized (lock) {
System.out.print(" " + itr);
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for (int itr = 2; itr < 51; itr = itr + 2) {
synchronized (lock) {
System.out.print(" " + itr);
try {
lock.notify();
if(itr==50)
break;
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
try {
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("\nPrinting over");
} catch (Exception e) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了实现这一点,上面两个线程的run方法必须一个接一个地调用,即它们需要同步并且我使用锁来实现.
代码的工作原理如下:t1.run打印奇数并通知任何等待线程它将释放锁,然后进入等待状态.
此时调用t2.run,它打印下一个偶数,通知其他线程它将要释放它所持有的锁,然后进入等待状态.
这一直持续到t2.run()中的itr达到50,此时我们的目标已经实现,我们需要杀死这两个线程.
通过断开,我避免在t2.run中调用lock.wait()并且t2线程因此关闭,控件现在将转到t1.run,因为它等待获取锁; 但是这里itr值将> 51并且我们将从run()中退出,从而关闭线程.
如果在t2.run()中没有使用break,虽然我们将在屏幕上看到数字1到50但是两个线程将进入死锁情况并继续处于等待状态.
aym*_*ric 14
我只想更改一些细节(这里不需要使用模运算符......):
public class Mythread {
public static void main(String[] args) {
Runnable r = new Runnable1();
Thread t = new Thread(r);
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}
class Runnable2 implements Runnable{
public void run(){
for(int i=0;i<11;i+=2) {
System.out.println(i);
}
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i=1;i<=11;i+=2) {
System.out.println(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)