一.线程类
1.使用多线程交替打印0-99。
使用Callable
public class MyCallable{
public static void main(String[] args){
MyCallable2 myCallable1=new MyCallable2();
FutureTask fk1=new FutureTask(myCallable1);
Thread t3=new Thread(fk1);
MyCallable2 myCallable2=new MyCallable2();
FutureTask fk2=new FutureTask(myCallable2);
Thread t4=new Thread(fk2);
t3.start();
t4.start();
try{
String str1=(String)fk1.get();
String str2=(String)fk2.get();
System.out.println(str1);
System.out.println(str2);
}catch(ExeutionException e){
e.printStackTrace();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class MyCallable2 implements Callable{
private static int i=0;
private static Object lock=new Object();
@Override
public Object call() throws Exception{
while(true){
synchronized(lock){
lock.notify();
if(i>100){
break;
}
System.out.println(Thread.currentThread()+" i="+i++);
try{
lock.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread()+" finished");
return "hello world "+Thread.currentThread();
}
}
使用Runnable
public class MyThread{
public static void main(String[] args){
MyRunnable myRunnable=new MyRunnable();
Thread thread1=new Thread(myRunnable);
Thread thread2=new Thread(myRunnable);
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable{
private static int i=0;
@Override
public void run(this){
notify();
if(i>=100){
break;
}
try{
System.out.println(Thread.currentThread()+" i="+i++);
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"执行完毕");
}
使用Thread
public class MyThread2{
static int i=0;
static Object lock=new Object();
public static void main(String[] args){
Thread t1=new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
while(true){
synchronized(lock){
lock.notify();
if(i>=100){
break;
}
try{
System.out.println(Thread.currentThread()+" i="+i++);
lock.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
});
Thread t2=new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
while(true){
synchronized(lock){
lock.notify();
if(i>=100){
break;
}
try{
System.out.println(Thread.currentThread()+" i="+i++);
lock.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
});
t1.start();
t2.start();
}
}
public class PrintNumThread extends Thread{
static int num=0;
static Object object=new Object();
@Override
public void run(){
while(true){
synchronized(object){
object.notify();
if(num<100){
num++;
System.out.println(Thread.currentThread().getName()+":"+num);
}else{
break;
}
try{
object.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args){
PrintNumThread p1=new PrintNumThread();
PrintNumThread p2=new PrintNumThread();
p1.start();
p2.start();
}
}