62,623
社区成员
发帖
与我相关
我的任务
分享
public class MyThread implements Runnable
{
String MyString="yes";
public void run()
{
this.MyString="no";
}
public static void main(String []args)
{
MyThread t=new MyThread();
new Thread(t).start();
for(int i=0;i<10;i++)
System.out.print(t.MyString);
}
}
public class MyThread implements Runnable
{
String MyString="yes";
Object mutex = new Object(); // 专门用于同步的对象。
boolean updated = false; // 数据是否已经更新?
public void run()
{
synchronize (mutex) {
this.MyString="no";
updated = true; // 已经更新,无须继续等待
mutex.notifyAll();
}
}
public static void main(String []args)
{
MyThread t=new MyThread();
new Thread(t).start();
for(int i=0;i<10;i++) {
System.out.print(t.MyString);
if (!updated) { // 如果还没有更新,则等待更新
synchronized (mutex) {
mutex.wait(); // 等待新线程更新数据完毕
}
}
}
}
}
7.锁其标
import java.lang.Thread;
public class Text1
{
public static void main(String [] args)
{
TestThread tt=new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TestThread implements Runnable //extends Thread
{
int tickets=100;
String str=new String("");
public void run()
{
while(true)
{
synchronized(str)//锁其标
{
if (tickets>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"is sealing tickets"+tickets--);
}
}
}
}
}
也可以在方法前面加个synchronized那就实现同步了 public synchronized void sals()