java 多线程:开两个线程,一个线程跑同步代码块,一个线程跑同步函数
代码如下:
package com.chnsys.thread1; public class JavaResearch01 { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); /*Thread t3 = new Thread(t); Thread t4 = new Thread(t);*/ t1.start(); try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t.flag = false; t2.start(); /*t3.start(); t4.start();*/ } } class Ticket implements Runnable{ private int tick = 100; Object obj = new Object(); boolean flag = true; @Override public void run() { // TODO Auto-generated method stub if(flag){ while(true){ //同步代码块 synchronized (this) { if(tick>0){ try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } System.out.println(Thread.currentThread().getName()+".....code : "+tick--); } } } } //show()函数 while(true){ show(); } } public synchronized void show(){ if(tick>0){ try { Thread.sleep(100); } catch (Exception e){ //TODO: handle exception } System.out.println(Thread.currentThread().getName()+"....show : "+tick--); } } }