class Demo implements Runnable {
//創(chuàng)建同步所需對象
Object obj = new Object();
int num = 100;
public void run(){
while(true){
//創(chuàng)建同步解決線程的安全問題,同步加在使用共享數(shù)據(jù)的代碼快上
synchronized(obj){
if(num>0){
try{Thread.sleep(6);}catch(InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"---"+num);
num--;
}
}
}
}
}
public class XianCheng {
public static void main(String[] args) {
Demo d=new Demo();
Thread th=new Thread(d);
Thread th1=new Thread(d);
Thread th2=new Thread(d);
th.start();
th1.start();
th2.start();
}
}
兩個線程币狠,在兩個不同的方法上進行
class Demo implements Runnable {
int num = 100;
boolean flag = true;
public void run() {
if (flag == true) {
while (true) {
synchronized (this) {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "---" + num);
num--;
}
}
}
} else {
show();
}
}
//當方法里的代碼都需要加同步,就可以 在方法上加同步释簿,非靜態(tài)方法加同步,同步鎖使用的是當前對象
//當在靜態(tài)方法上加同步時僻他,同步鎖是類名加class
private synchronized void show() {
// TODO Auto-generated method stub
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "---" + num);
num--;
}
}
}
public class XianCheng {
public static void main(String[] args) {
Demo d = new Demo();
Thread th1 = new Thread(d);
Thread th2 = new Thread(d);
th1.start();
//由于cpu先是在主線程上運行的兽狭,當開啟第一個線程時cpu不一定立刻執(zhí)行
//這時加一個“睡眠”,保證cpu進入第一個線程
try{Thread.sleep(6);}catch(InterruptedException e){
}
th2.start();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者