62,614
社区成员
发帖
与我相关
我的任务
分享
public class TestRun {
private boolean stx;
private Thread t1;
private Thread t2;
public void test() {
t1 = new ReadThread();
t2 = new WriteThread();
t1.start();
t2.start();
}
class ReadThread extends Thread {
public void run() {
long temp = System.currentTimeMillis();
while (!stx) {
if (System.currentTimeMillis() - temp >= 2000) {
break;
}
}
System.out.println("stx=" + stx);
}
}
class WriteThread extends Thread {
public void run() {
Random rm = new Random();
while(true){
if(rm.nextInt()%5==0){
stx=true;
}
}
}
}
}
package com.study.thread;
public class ThreadSleep {
public static void main(String[] args) {
Thread t1 = new T1();
Thread t2 = new T2(t1);
t1.start();
t2.start();
}
}
class T1 extends Thread{
public void run(){
while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("线程被中断信号唤醒");
break;
}
}
System.out.println("等待check信号的线程结束");
}
}
class T2 extends Thread{
private Thread t;
public T2(Thread t){
this.t = t;
}
public void run(){
Method m = new Method();
for(int i = 0; ;i++){
if(m.check(i)){
t.interrupt();
break;
}
}
}
}
class Method{
public boolean check(int i){
System.out.println("执行check方法.....");
if(i >= 10){
return true;
}else{
return false;
}
}
}
import java.util.Date;
public class Test2 {
private static long s = (new Date()).getTime();
private static boolean check(){
return false;
}
public static void main(String[] args) {
while(!check()){
if((new Date().getTime())==(s+2000)){
/*
*这3个System是判断是不是2秒之后结束的循环
*/
// System.out.println("now=="+s);
// System.out.println(new Date(s));
// System.out.println(new Date(s+2000));
break;
}
}
}
}