public class TestSy implements Runnable
{
Tim tim = new Tim();
public static void main(String[] args)
{
TestSy f = new TestSy();
Thread f1 = new Thread(f);
Thread f2 = new Thread(f);
f1.setName("111");
f2.setName("222");
f1.start();
f2.start();
System.out.println("Hello World!");
}
public void run() {
//System.out.println("sda");
tim.add(Thread.currentThread().getName());
}
}class Tim
{
private static int num = 0;
public synchronized void add(String name) {
num ++;
try
{
Thread.sleep(1);
}
catch (InterruptedException k)
{
System.out.println(name + "你是第" + num + "个使用线程");
}
}
}
{
Tim tim = new Tim();
public static void main(String[] args)
{
TestSy f = new TestSy();
Thread f1 = new Thread(f);
Thread f2 = new Thread(f);
f1.setName("111");
f2.setName("222");
f1.start();
f2.start();
System.out.println("Hello World!");
}
public void run() {
//System.out.println("sda");
tim.add(Thread.currentThread().getName());
}
}class Tim
{
private static int num = 0;
public synchronized void add(String name) {
num ++;
try
{
Thread.sleep(1);
}
catch (InterruptedException k)
{
System.out.println(name + "你是第" + num + "个使用线程");
}
}
}
Tim tim = new Tim(); public static void main(String[] args){
TestSy f = new TestSy();
Thread f1 = new Thread(f);
Thread f2 = new Thread(f);
f1.setName("111");
f2.setName("222");
f1.start();
f2.start();
System.out.println("Hello World!");
}
private int i = 0 ;
public void run(){
while(i ++ < 100){
tim.add(Thread.currentThread().getName());
// Thread.currentThread().interrupt();
}
}
}class Tim{
private static int num = 0; public synchronized void add(String name){
num++;
try{
Thread.sleep(100);
System.out.println(name + "你是第" + num + "个使用num的");
}catch(InterruptedException k){
System.out.println("线程" + name + "被打断");
}
}
}
把打印语句加到Thread.sleep(1000)的前面来。
System.out.println(name + "你是第" + num + "个使用线程");
Thread.sleep(1000);
那你想得到什么样的打印效果呢?
{
Tim tim = new Tim(); public static void main(String[] args)
{
TestSy f = new TestSy();
Thread f1 = new Thread(f);
Thread f2 = new Thread(f);
f1.setName("111");
f2.setName("222");
f1.start();
f2.start();
System.out.println("Hello World!");
}
public void run() {
//System.out.println("sda");
synchronized(tim){
tim.add(Thread.currentThread().getName());
}
}
} class Tim
{
private static int num = 0;
public void add(String name) {
num ++;
try
{
Thread.sleep(1);
System.out.println(name + "你是第" + num + "个使用线程");
}
catch (InterruptedException k)
{
k.printStackTrace();
}
}
}