本文介绍了Java线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用2个线程显示我的名字和姓氏。一旦用户点击ctrl与一些密钥程序应该终止。请建议我开始这个。这是我的代码,它只显示一个版本。但是我希望在用户按下某个键之前显示它。
i want to display my first name and last name using 2 threads. Once user click ctrl with some key programe should be terminate. Please advice me to begin this. here is my code and it is display only one tome. but i want to display this into until user press some key.
class Thread_Ex11{
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "gayan");
Thread t2 = new Thread(new MyRunnable(), "suranga");
t1.start();
try {
t1.join(2000);
t2.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
t1.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName());
}
}
}
什么我试过了:
我这个程序编译的输出
这是一个
这是两个
但是我想出去的是
这是一个
这是两个
这是一个
这是两个
等....
终止
What I have tried:
my out put of this programme compiling
this is one
this is two
but i want out put is
this is one
this is two
this is one
this is two
etc....
terminated
推荐答案
public class Thread_Ex {
public static void main(String [] args) {
Thread t1 = new Thread(new MyRunnable(), "gayan");
Thread t2 = new Thread(new MyRunnable(), "suranga");
t1.start();
t2.start();
while (true) {
try {
System.in.read();
t1.interrupt();
t2.interrupt();
}
catch (Exception eee) {
//
}
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(200);
}
catch (InterruptedException zz) {
//
}
if (Thread.interrupted()) {
System.out.println("interrupted");
break;
}
}
}
}
这篇关于Java线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!