线程休眠
package cglib;
import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit;public class jiekou {
public static void main(String args[]) throws InterruptedException { DateFormat format = new SimpleDateFormat("HH:mm:ss"); System.out.println(Thread.currentThread().getName()+"1 Run at"+format.format(new Date())); Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+"2 Run at"+format.format(new Date())); TimeUnit.SECONDS.sleep(4); System.out.println(Thread.currentThread().getName()+"3 Run at"+format.format(new Date())); } }
main1 Run at14:00:44
main2 Run at14:00:45 main3 Run at14:00:49
死锁:
package cglib;
public class jiekou {
private static String A="A"; private static String B="B"; public static void main(String[] args){ new jiekou().deadLock(); } private void deadLock(){ System.out.print("2"); Thread t1= new Thread(new Runnable(){ @SuppressWarnings("static-access") public void run(){ synchronized(A){ try{ Thread.currentThread().sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); } synchronized(B){ System.out.print("1"); } } } }); Thread t2= new Thread(new Runnable(){ public void run(){ synchronized(B){ synchronized(A){ System.out.println("2"); } } } }); t1.start(); t2.start(); } }
package cglib;
import java.util.ArrayList;
import java.util.List; import java.util.concurrent.atomic.AtomicInteger;public class jiekou {
private AtomicInteger atomicI= new AtomicInteger(0); private int i=0; public static void main(String[] args){ final jiekou cas = new jiekou(); //引用类型的变量cas,则在对其初始化之后便不能再让其指向另一个对象。 List<Thread> ts=new ArrayList<Thread>(600); long start =System.currentTimeMillis(); for(int j=0;j<100;j++){ Thread t=new Thread(new Runnable(){ public void run(){ for(int i=0;i<10000;i++){ cas.count(); cas.safeCount(); } } }); //System.out.println("放入前"); //System.out.println(t); ts.add(t); //System.out.println("放入后"); //System.out.println(ts); } for(Thread t:ts){ System.out.println("开始"); t.start(); System.out.println(t); } for(Thread t:ts){ try{ System.out.println("join"); t.join(); System.out.println(t); } catch(InterruptedException e){ e.printStackTrace(); } } System.out.println(cas.i); System.out.println(cas.atomicI.get()); System.out.println(System.currentTimeMillis()-start); } private void safeCount(){ for(;;){ int i=atomicI.get(); boolean suc=atomicI.compareAndSet(i, ++i); if(suc){ break; } } } private void count(){ i++; } } 输出:994468
1000000 57
线程优先级:
package cglib;
import java.util.ArrayList;
import java.util.List; import java.util.concurrent.TimeUnit; public class jiekou { private static volatile boolean notStart=true; private static volatile boolean notEnd=true; public static void main(String[] args)throws Exception{ List<Job> jobs=new ArrayList<Job>(); for(int i=0;i<10;i++){ int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY; Job job=new Job(priority); jobs.add(job); Thread thread=new Thread(job,"Thread:"+i); thread.setPriority(priority); thread.start(); } notStart=false; TimeUnit.SECONDS.sleep(10); notEnd=false; for(Job job:jobs){ System.out.println("Job Priority"+job.priority+",Count:"+job.jobCount); } } static class Job implements Runnable{ private int priority; private long jobCount; public Job(int priority){ this.priority=priority; } public void run(){ while(notStart){ Thread.yield(); } while(notEnd){ Thread.yield(); jobCount++; } } } } 输出:Job Priority1,Count:1652294
Job Priority1,Count:130195 Job Priority1,Count:4950103 Job Priority1,Count:5048168 Job Priority1,Count:3725580 Job Priority10,Count:5288083 Job Priority10,Count:4991636 Job Priority10,Count:5068902 Job Priority10,Count:5053565 Job Priority10,Count:5288773
线程状态
package cglib;
import java.util.concurrent.TimeUnit; public class jiekou { public static void main(String[] arg){ new Thread(new TimeWaiting(),"TimeWaitingThread").start(); new Thread(new Waiting(),"WaitingThread").start(); new Thread(new Blocked(),"BlockedThread-1").start(); new Thread(new Blocked(),"BlockedThread-2").start(); } static class TimeWaiting implements Runnable{ public void run(){ while(true){ SleepUtils.second(100); } } } static class Waiting implements Runnable{ public void run(){ while(true){ synchronized(Waiting.class){ try{ Waiting.class.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } } } } static class Blocked implements Runnable{ public void run(){ synchronized(Blocked.class){ while(true){ SleepUtils.second(100); } } } } public static class SleepUtils{ public final static void second(long seconds) { try{ TimeUnit.SECONDS.sleep(seconds); } catch(InterruptedException e){ } } } } 守护线程package cglib;
import java.util.concurrent.TimeUnit; public class jiekou { public static void main(String[] args){ Thread thread = new Thread(new DaemonRunner(),"DaemonRunner"); thread.setDaemon(true); System.out.println("DaemonThread."); thread.start(); } static class DaemonRunner implements Runnable{ public void run(){ try{ SleepUtils.second(10); }finally{ System.out.println("DaemonThread finally run."); } } } public static class SleepUtils{ public final static void second(long seconds) { try{ TimeUnit.SECONDS.sleep(seconds); } catch(InterruptedException e){ } } } }
package cglib;
import java.util.concurrent.TimeUnit; public class jiekou { public static void main(String[] args)throws Exception{ Thread sleepThread=new Thread(new SleepRunner(),"SleepThread"); sleepThread.setDaemon(true); Thread busyThread=new Thread(new BusyRunner(),"BusyThread"); busyThread.setDaemon(true); sleepThread.start(); busyThread.start(); TimeUnit.SECONDS.sleep(5); sleepThread.interrupt(); busyThread.interrupt(); System.out.println("SleepThread interrupted is "+sleepThread.isInterrupted()); System.out.println("BusyThraed interrupted is "+busyThread.isInterrupted()); SleepUtils.second(2); } static class SleepRunner implements Runnable{ public void run(){ while(true){ SleepUtils.second(10); } } } static class BusyRunner implements Runnable{ public void run(){ while(true){ } } } public static class SleepUtils{ public final static void second(long seconds) { try{ TimeUnit.SECONDS.sleep(seconds); } catch(InterruptedException e){ } } } }
中断
输出:SleepThread interrupted is false
BusyThraed interrupted is true
挂起等
package cglib;
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class jiekou { @SuppressWarnings("deprecation") public static void main(String[] args){ DateFormat format = new SimpleDateFormat("HH:mm:ss"); Thread printThread=new Thread(new Runner(),"PrintThread"); printThread.setDaemon(true); printThread.start(); try { //System.out.println(Thread.currentThread().getName()+"qeqeq Run at"+format.format(new Date())); TimeUnit.SECONDS.sleep(3); //System.out.println(Thread.currentThread().getName()+"heh Run at"+format.format(new Date())); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } printThread.suspend(); System.out.println("main suspend PrintThread at "+format.format(new Date())); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } printThread.resume(); System.out.println("main resume PrintThread at"+format.format(new Date())); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } printThread.stop(); System.out.println("main stop PrintThread at "+format.format(new Date())); } static class Runner implements Runnable{ public void run(){ DateFormat format = new SimpleDateFormat("HH:mm:ss"); while(true){ System.out.println(Thread.currentThread().getName()+" Run at"+format.format(new Date())); SleepUtils.second(1); //System.out.println(Thread.currentThread().getName()+" 睡了Run at"+format.format(new Date())); } } } public static class SleepUtils{ public final static void second(long seconds) { try{ TimeUnit.SECONDS.sleep(seconds); } catch(InterruptedException e){ } } } }
输出:
PrintThread Run at11:20:30
PrintThread Run at11:20:31 PrintThread Run at11:20:32 main suspend PrintThread at 11:20:33 PrintThread Run at11:20:36 main resume PrintThread at11:20:36 PrintThread Run at11:20:37 PrintThread Run at11:20:38 main stop PrintThread at 11:20:39安全地终止线程
package cglib;
import java.util.concurrent.TimeUnit;
public class jiekou { public static void main(String[] args) throws Exception{ Runner one = new Runner(); Thread countThread= new Thread(one,"CountThread"); //System.out.println(Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(1); // System.out.println(Thread.currentThread().getName()); countThread.start(); // System.out.println(Thread.currentThread().getName()); countThread.interrupt(); Runner two = new Runner(); countThread=new Thread(two,"CountThread"); countThread.start(); TimeUnit.SECONDS.sleep(1); two.cancle(); } private static class Runner implements Runnable{ private long i; private volatile boolean on=true; public void run(){ while(on&&!Thread.currentThread().isInterrupted()){ i++; } System.out.println("Count i="+i); } public void cancle(){ on=false; } } }输出:
Count i=0
Count i=20159146
package cglib;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.concurrent.TimeUnit;public class jiekou {
static boolean flag =true; static Object lock=new Object(); public static void main(String[] args)throws Exception{ Thread waitThread=new Thread(new Wait(),"WaitThread"); waitThread.start(); TimeUnit.SECONDS.sleep(1); Thread notifyThread=new Thread(new Notify(),"NotifyThread"); notifyThread.start(); } static class Wait implements Runnable{ public void run(){ synchronized(lock){ while(flag){ try{ System.out.println(Thread.currentThread()+" flag is true.wait @"+new SimpleDateFormat("HH:mm:ss").format(new Date())); lock.wait(); }catch(InterruptedException e){ } } } System.out.println(Thread.currentThread()+"flag is false.running@"+new SimpleDateFormat("HH:mm:ss").format(new Date())); } } static class Notify implements Runnable{ public void run(){ synchronized(lock){ System.out.println(Thread.currentThread()+"hold lock.notify@"+new SimpleDateFormat("HH:mm:ss").format(new Date())); lock.notifyAll(); flag=false; SleepUtils.second(5); } synchronized(lock){ System.out.println(Thread.currentThread()+"hold lock again.sleep@"+new SimpleDateFormat("HH:mm:ss").format(new Date())); SleepUtils.second(5); } } public static class SleepUtils{ public final static void second(long seconds) { try{ TimeUnit.SECONDS.sleep(seconds); } catch(InterruptedException e){ } } } } } Thread[WaitThread,5,main] flag is true.wait @12:51:45 Thread[NotifyThread,5,main]hold lock.notify@12:51:46 Thread[NotifyThread,5,main]hold lock again.sleep@12:51:51 Thread[WaitThread,5,main]flag is false.running@12:51:56管道输入输出
package cglib;
import java.io.IOException;
import java.io.PipedReader; import java.io.PipedWriter; public class jiekou { public static void main(String[] args) throws Exception{ PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(); out.connect(in); Thread printThread = new Thread(new Print(in),"PrintThread"); printThread.start(); int receive=0; try{ while((receive=System.in.read())!=-1){ out.write(receive); } }finally{ out.close(); } } static class Print implements Runnable{ private PipedReader in; public Print(PipedReader in){ this.in=in; } public void run(){ int receive=0; try{ while((receive=in.read())!=-1){ System.out.print((char)receive); } }catch(IOException ex){ } } } }
join
package cglib;
public class jiekou {
public static void main(String[] args) throws Exception{ Thread previous =Thread.currentThread(); System.out.println(Thread.currentThread().getName()+"0-previous"); for(int i=0;i<10;i++){ Thread thread = new Thread(new Domino(previous),String.valueOf(i)); thread.start(); previous=thread; System.out.println(previous+":previous"); } } static class Domino implements Runnable{ private Thread thread; public Domino(Thread thread){ this.thread=thread; } public void run(){ try{ thread.join(); System.out.println(thread+":thread join"); }catch(InterruptedException e){ } System.out.println(Thread.currentThread().getName()+"terminate."); } } }
输出:
main0-previous
Thread[0,5,main]:previous Thread[1,5,main]:previous Thread[2,5,main]:previous Thread[3,5,main]:previous Thread[4,5,main]:previous Thread[5,5,main]:previous Thread[6,5,main]:previous Thread[7,5,main]:previous Thread[8,5,main]:previous Thread[9,5,main]:previous Thread[main,5,]:thread join 0terminate. Thread[0,5,]:thread join 1terminate. Thread[1,5,]:thread join 2terminate. Thread[2,5,]:thread join 3terminate. Thread[3,5,]:thread join 4terminate. Thread[4,5,]:thread join 5terminate. Thread[5,5,]:thread join 6terminate. Thread[6,5,]:thread join 7terminate. Thread[7,5,]:thread join 8terminate. Thread[8,5,]:thread join 9terminate.ThreadLocal
package cglib;
import java.util.concurrent.TimeUnit;
public class jiekou {
private static final ThreadLocal<Long> TIME_THREADLOCAL=new ThreadLocal<Long>(){ protected Long initialValue(){ return System.currentTimeMillis(); } }; public static final void begin(){ TIME_THREADLOCAL.set(System.currentTimeMillis()); System.out.println("哈哈: "+System.currentTimeMillis()); System.out.println("哈哈: "+TIME_THREADLOCAL.get()); } public static final long end(){ System.out.println("呵呵: "+System.currentTimeMillis()); System.out.println("呵呵: "+TIME_THREADLOCAL.get()); return System.currentTimeMillis()-TIME_THREADLOCAL.get(); } public static void main(String[] args)throws Exception{ jiekou.begin(); TimeUnit.SECONDS.sleep(1); System.out.println("嘻嘻: "+TIME_THREADLOCAL.get()); System.out.println("Cost: "+jiekou.end()+"mills"); } }输出:
哈哈: 1472363616988
哈哈: 1472363616988 嘻嘻: 1472363616988 呵呵: 1472363617990 呵呵: 1472363616988 Cost: 1002mills